<?php

namespace app\mini\controller\dealer;

use app\common\controller\ApiController;
use app\common\service\annotation\ControllerAnnotation;
use app\company\model\CompanyOrder;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="经销商配送管理")
 */
class Delivery extends ApiController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function list(): Json
    {
        $get = $this->request->get();
        $where = [];
        if(!empty($get['start_time']) && !empty($get['end_time'])) {
            $start = strtotime($get['start_time'].'00:00:00');
            $end = strtotime($get['end_time'].'23:59:59');
            $where[] = ['co.create_time','between',[$start,$end]];
        }
        $list = (new CompanyOrder())->alias('co')
            ->field('co.id,co.create_time,s.name as store_name,d.name as driver_name,log.money,s.address')
            ->join('store s','co.store_id = s.id','left')
            ->join('driver d','co.driver_id = d.id','left')
            ->join('delivery_log log','co.id = log.company_order_id','inner')
            ->where($where)
            ->where('co.dealer_id',$this->uid)
            ->where('delivery_status',4)
            ->paginate($get['limit']??15);
        return $this->success($list);
    }

    public function detail($id): Json
    {
        $list = (new CompanyOrder())->field('id,driver_id,store_id,dealer_id,order_no,delivery_amount,receive_type,create_time')->with([
            'store' => function($query){
                $query->field('id,name,address');
            },
            'driver' => function($query){
                $query->field('id,name');
            },
            'dealer' => function($query){
                $query->field('id,name');
            },
            'detail' => function($query){
                $query->field('id,company_order_id,dealer_goods_id,dealer_goods_spec_id,num,true_price,delivery_num')->with([
                    'goods' => function($query){
                        $query->field('id,name');
                    },
                    'goodsSpec' => function($query){
                        $query->field('id,name,unit');
                    },
                ]);
            },
            'deliveryLog' => function($query){
                $query->field('id,company_order_id,money,image,remark');
            },
        ])->append(['receive_type_text'])->where('id',$id)->where('delivery_status',4)->find();
        return $this->success($list);
    }
}